#pragma once

#include <iostream>
#include <string>
#include <poll.h>
#include "log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

const int gdefaultfd = -1;

#define MAX 4096

class PollServer
{
public:
    PollServer(uint16_t port)
        : _port(port), _listen_socket(std::make_unique<TcpSocket>()), _is_running(false)
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpsocketMethood(_port);
        for(int i = 0; i < MAX; i++)
        {
            _fds[i].fd = gdefaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        _fds[0].fd = _listen_socket->Fd();
        _fds[0].events |= POLLIN;
    }

    void Loop()
    {
        _is_running = true;
        int timeout = 1000;
        while (_is_running)
        {
            // 不能让accept阻塞检查新连接到来，让select来进行就绪事件检测

            int n = poll(_fds, MAX, timeout);
            switch (n)
            {
            case 0:
                std::cout << "timeout..." << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                std::cout << "有事件就绪了!" << std::endl;
                Dispatcher(); // 将已经就绪的事件派发给指定的模块
                break;
            }
        }
        _is_running = false;
    }

    void Accept()
    {
        InetAddr client;
        int newfd = _listen_socket->accepter(&client);
        if (newfd < 0)
            return;
        else
        {
            std::cout << "获得了一个新的连接: " << newfd << "client info: " << client.AddrStr() << std::endl;
            int pos = -1;
            for (int j = 0; j < MAX; j++)
            {
                if (_fds[j].fd == gdefaultfd)
                {
                    pos = j;
                    break;
                }
            }
            if (pos == -1)
            {
                LOG(ERROR, "服务器满载");
                close(newfd);
            }
            else
            {
                _fds[pos].fd = newfd;
                _fds[pos].events = POLLIN;
            }
        }
    }

    void Recver(int who)
    {
        // 实际上这里的读并不完善，要完善得有协议
        char buffer[1024];
        ssize_t n = recv(_fds[who].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;

            std::string message = "echo# ";
            message += buffer;
            send(_fds[who].fd, message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(DEBUG, "客户端退出, sockfd: %d\n", _fds[who].fd);
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = _fds[who].revents = 0;
        }
        else
        {
            LOG(DEBUG, "客户端读取出错, sockfd: %d\n", _fds[who].fd);
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = _fds[who].revents = 0;
        }
    }

    void Dispatcher()
    {
        for (size_t i = 0; i < MAX; i++)
        {
            if (_fds[i].fd == gdefaultfd)
                continue;
            if (_fds[i].fd == _listen_socket->Fd())
            {
                if (_fds[i].revents & POLLIN)
                {
                    Accept();
                }
            }
            else
            {
                if (_fds[i].revents & POLLIN)
                {
                    Recver(i);
                }
            }
        }
    }

    ~PollServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;

    bool _is_running;
    struct pollfd _fds[MAX]; // 这里可以定义成指针，得到柔性数组
};